<template>
  <div class="evaluationInfo_container">
    <basicinfo :form-data="form"></basicinfo>
    <el-card
      class="box-card"
      shadow="always"
      style="background: #fafafa; margin-top: 20px"
    >
      <template #header>
        <div class="card-header" style="padding-bottom: 4px">
          <div
            class="card-header"
            style="
              padding-bottom: 4px;
              display: flex;
              align-items: center;
              justify-content: space-between;
            "
          >
            <span>服务项目</span>
            <el-button
              type="primary"
              size="small"
              plain
              @click="add"
              v-if="status != '2'"
              >新增</el-button
            >
          </div>
        </div>
        <div>
          <el-table
            v-loading="loading"
            :data="servicePlanList"
            stripe
            border
            max-height="250"
          >
            <el-table-column
              label="序号"
              type="index"
              width="80"
              align="center"
            />
            <el-table-column label="服务项目" align="center" width="300">
              <template #default="scope">
                <el-select
                  v-model="scope.row.serviceItemId"
                  :disabled="status=='2'"
                  clearable
                  @change="
                    (value) => changeServiceName(value, scope.$index, scope.row)
                  "
                  placeholder="请选择服务项目"
                  style="width: 250px"
                >
                  <el-option
                    v-for="dict in serviceList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="单价（元）"
              align="center"
              prop="unitPrice"
              width="100"
            />
            <el-table-column label="单位" align="center" width="100">
              <template #default="scope">
                <span>
                  {{
                    bed_uint.find((item) => item.value == scope.row.unit)
                      ? bed_uint.find((item) => item.value == scope.row.unit)
                          .label
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="社区站点佣金（元）"
              align="center"
              prop="commission"
              width="150"
            />
            <el-table-column label="服务频率" width="180" align="center">
              <template #default="scope">
                <div style="width: 160px">
                  <el-select
                      :disabled="status=='2'"
                    v-model="scope.row.serviceFrequency"
                    clearable
                    placeholder="请选择服务频率"
                    style="width: 150px"
                  >
                    <el-option
                      v-for="dict in service_frequency"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="服务次数" align="center" width="150">
              <template #default="scope">
                <el-input
                    :disabled="status=='2'"
                  v-model.number="scope.row.serviceTimes"
                  @change="(value) => changNumber(value, scope.row)"
                  placeholder="请输入服务次数"
                  clearable
                />
              </template>
            </el-table-column>
            <el-table-column
              label="备注"
              align="center"
              prop="notes"
              width="600"
            >
              <template #default="scope">
                <el-input
                    :disabled="status=='2'"
                  v-model="scope.row.notes"
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 8 }"
                  placeholder="请输入备注"
                  show-word-limit
                  maxlength="500"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <span v-if="status=='2'">
                  <el-button
                      link
                      type="primary"
                      @click="infoPlan(scope.row, scope.$index)"
                  >查看服务时间</el-button>
                </span>
                <span v-else>
                   <el-button
                       link
                       type="primary"
                       @click="setPlan(scope.row, scope.$index)"
                   >制定服务时间</el-button
                   >
                <el-button
                    link
                    type="danger"
                    @click="del(scope.row, scope.$index)"
                >删除</el-button
                >
                </span>

              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </el-card>
    <div style="text-align: right; margin-top: 30px; margin-right: 30px">
      <el-button
        type="primary"
        @click="submitFormDebounceHandler"
        v-if="status != '2'"
        >确 定</el-button
      >
      <el-button @click="cancel">返 回 </el-button>
    </div>
    <el-dialog
      v-model="open"
      title="设置服务时间"
      append-to-body
      width="600px"
      v-if="open"
      @close="cancel"
      :close-on-click-modal="false"
    >
      <div>
        <el-table v-loading="loading" :data="postList" stripe border>
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
          />
          <el-table-column label="日期" align="center">
            <template #default="scope">
              <el-select
                v-model="scope.row.date"
                clearable
                placeholder="请选择计划状态"
                style="width: 150px"
                :disabled="status=='2'"
                v-if="serviceFrequency == '1'"
              >
                <el-option
                  v-for="dict in plan_week"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
              <el-select
                v-model="scope.row.date"
                clearable
                :disabled="status=='2'"
                placeholder="请选择计划状态"
                style="width: 150px"
                v-if="serviceFrequency == '2'"
              >
                <el-option
                  v-for="dict in plan_day"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
              <el-input
                v-if="serviceFrequency == '0'"
                placeholder="请选择"
                v-model="scope.row.date"
                :disabled="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="服务开始时间" width="250" align="center">
            <template #default="scope">
              <el-time-picker
                v-model="scope.row.beginTime"
                :disabled="status=='2'"
                placeholder="服务开始时间"
                value-format="HH:mm:ss"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDebounceHandler"
            >确 定</el-button
          >
          <el-button @click="goCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss" name="servicePlanDetail">
.evaluationInfo_container {
  padding: 20px;
}
</style>
<script setup>
import { debounce } from "@/utils/debounce.js";

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
import {
  getServiceItemSelectOptions,
  servicePlanDataSave,
  servicePlanSave,
} from "@/api/homebedsign/index";
const { bed_uint, service_frequency, plan_week, plan_day } = proxy.useDict(
  "bed_uint",
  "service_frequency",
  "plan_week",
  "plan_day",
);
import basicinfo from "../evaluation/basicinfo.vue";

const serviceList = ref([]);
const servicePlanList = ref([]);
const loading = ref(false);
const open = ref(false);
const postList = ref([]);
const serviceFrequency = ref("");
const postListLength = ref(0);
const Flagindex = ref(0);
const status = ref("");

const data = reactive({
  form: {},
});

const { form } = toRefs(data);
const submitDebounceHandler = debounce(submitForm, 500);
const submitFormDebounceHandler = debounce(submitFormDebounce, 500);
function submitFormDebounce() {
  for (let i in servicePlanList.value) {
    if (!servicePlanList.value[i].serviceItemId) {
      proxy.$modal.msgError(`请选择第${i - 0 + 1}个服务项目`);
      return false;
    }
    if (!servicePlanList.value[i].serviceFrequency) {
      proxy.$modal.msgError(`请选择第${i - 0 + 1}个服务频率`);
      return false;
    }
    if (
      !servicePlanList.value[i].serviceTimes &&
      servicePlanList.value[i].serviceTimes > 0
    ) {
      proxy.$modal.msgError(`请填写${i - 0 + 1}个服务次数并且服务次数大于0`);
      return false;
    }
    if (
        !servicePlanList.value[i].notes &&
        servicePlanList.value[i].notes.length > 500
    ) {
      proxy.$modal.msgError(`第${i - 0 + 1}个备注超过500个字符`);
      return false;
    }
  }
  let obj = {
    id: form.value.id,
    servicePlanList: servicePlanList.value,
  };
  servicePlanDataSave(obj).then((res) => {
    proxy.$modal.msgSuccess(`制定成功`);
    router.go(-1);
  });
}
function submitForm() {
  for (let i in postList.value) {
    if (serviceFrequency.value != "0") {
      if (!postList.value[i].date) {
        proxy.$modal.msgError(`请选择第${i - 0 + 1}个服务日期`);
        return false;
      }
    }
    if (!postList.value[i].beginTime) {
      proxy.$modal.msgError(`请选择第${i - 0 + 1}个服务开始时间`);
      return false;
    }
  }
  servicePlanList.value[Flagindex.value].serviceTimeList = postList.value;
  postList.value = [];
  open.value = false;
}
function cancel() {
  router.go(-1);
}
function del(data, index) {
  servicePlanList.value.splice(index, 1);
}
function setPlan(data, index) {
  Flagindex.value = index;
  if (!data.serviceItemId) {
    proxy.$modal.msgError("请选择服务项目");
    return false;
  }
  if (!data.serviceFrequency) {
    proxy.$modal.msgError("请选择服务频率");
    return false;
  }
  serviceFrequency.value = data.serviceFrequency;
  if (data.serviceTimeList.length > 0) {
    postList.value = data.serviceTimeList;
  } else {
    postListLength.value = data.serviceTimes ? data.serviceTimes : 0;
    let arr = [];
    for (let i = 0; i < postListLength.value; i++) {
      arr.push({
        date: "",
        beginTime: "",
      });
    }
    postList.value = arr;
    if (serviceFrequency.value == "0") {
      for (let i in postList.value) {
        postList.value[i].date = "";
      }
    }
  }

  open.value = true;
}
function infoPlan(data){
  serviceFrequency.value = data.serviceFrequency;
  if (data.serviceTimeList.length > 0) {
    postList.value = data.serviceTimeList;
  }
  open.value=true
}
function goCancel() {
  open.value = false;
  postList.value = [];
}
function getSevicePlan(data) {
  servicePlanSave(data).then((res) => {
    form.value = res.servicePlanInfo;
    servicePlanList.value=res.servicePlanInfo.servicePlanList
  });
}
function changeServiceName(val, index, data) {
  data.commission = serviceList.value.find(
    (item) => item.id == val,
  )?.commission;
  data.unitPrice = serviceList.value.find((item) => item.id == val)?.unitPrice;
  data.unit = serviceList.value.find((item) => item.id == val)?.unit;
  data.serviceItemName = serviceList.value.find((item) => item.id == val)?.name;
}
function changNumber(val, data) {
  if (!(typeof (val - 0) == "number" && !isNaN(val - 0))) {
    proxy.$modal.msgError("请正确输入数量");
    data.serviceTimes = "";
  }
}
function add() {
  servicePlanList.value.push({
    homeBedApplyId: form.value.id,
    serviceItemId: "",
    serviceItemName: "",
    serviceFrequency: "",
    serviceTimes: "",
    notes: "",
    serviceTimeList: [],
  });
}
function getServiceItemSelectOptionsData() {
  getServiceItemSelectOptions().then((res) => {
    serviceList.value = res.serviceItemList;
  });
}
const stopWatch = watch(
  () => route,
  (newVal, oldVal) => {
    getSevicePlan(newVal.params.id);
    status.value = newVal.params.status;
  },
  { immediate: true },
);
getServiceItemSelectOptionsData();
onBeforeUnmount(() => {
  stopWatch();
});
</script>
